/**
 *
 */
package pt.mleiria.core.socket;

import java.io.DataOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author manuel
 *
 */
public class VoiceClient implements ClientSocket {

    private Socket clientSocket;
    private boolean stop = false;

    /**
     *
     * @return @throws Exception
     */
    public void setClientSocket() throws Exception {
        Logger.getLogger(ClientSocket.class.getName()).log(Level.INFO, "Just connected to ");
        Logger.getLogger(ClientSocket.class.getName()).log(Level.INFO, "Connecting to " + ClientSocket.VOICE_SERVER
                + " on port " + ClientSocket.PORT_VOICE_SERVER);
        clientSocket = new Socket(ClientSocket.VOICE_SERVER, ClientSocket.PORT_VOICE_SERVER);
        Logger.getLogger(ClientSocket.class.getName()).log(Level.INFO, "Just connected to "
                + clientSocket.getRemoteSocketAddress());
    }

    /**
     * To send data through the socket to the server, the VoiceClient example
     * needs to write to the PrintWriter To get the server's response,
     * EchoClient reads from the BufferedReader object stdIn,
     *
     * @param command
     * @return
     * @throws Exception
     */
    public int sendVoiceCommand(final String command) throws Exception {
        if(stop){
            return 0;
        }
        OutputStream outToServer = clientSocket.getOutputStream();
        DataOutputStream out = new DataOutputStream(outToServer);
        Logger.getLogger(VoiceClient.class.getName()).log(Level.INFO, "voice command:" + command);
        out.writeUTF(command);
        Thread.sleep(1000);
        return 1;
    }
    
    public void close() throws Exception{
        clientSocket.close();
    }
    
    public void stopVoice(){
        stop = true;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        try {

            VoiceClient vc = new VoiceClient();
            vc.setClientSocket();
            vc.sendVoiceCommand("Bom dia Carolina. Dormiste bem? Hoje tens natação");
            vc.setClientSocket();
            vc.sendVoiceCommand("Bom dia Rodrigo. Dormiste bem? Hoje tens música até às oito e trinta.");
            vc.setClientSocket();
            vc.sendVoiceCommand("Bom dia Guilherme. Não te esqueças das baquetas porque tens aula de percurssão.");
            vc.setClientSocket();
            vc.sendVoiceCommand("ml_kill");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
